<template>
  <div class="environment-monitor">
    <div class="header-actions">      
      <h3>
        <div>任务名称： {{ getTaskName() || monitorData.sceneName }}</div>
        <div style="margin-top: 10px;">漏洞名称： {{ vuln_title }}
        <el-button
          size="small"
          type="primary"
          @click="handleViewDetails(monitorData)"
        >
          漏洞详情
        </el-button>
        </div>
      </h3>
    </div>
    <!-- <el-card shadow="hover" style="margin-bottom: 20px">
      <div class="selectBox">
        <span>验证环境</span>
        <el-select
          v-model="value"
          placeholder="请选择漏洞验证的环境"
          style="width: 240px"
        >
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </div>
      <div class="selectBox">
        <span>漏洞</span>
        <el-select
          v-model="value"
          placeholder="请选择验证的漏洞"
          style="width: 240px"
        >
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </div>
      <div>
        <el-button type="primary">执行验证</el-button>
      </div>
    </el-card> -->

    <div style="display: flex">
      <!-- 验证状态卡片 -->
      <!-- <el-card style="width: 300px; margin-right: 20px">
        <template #header>
          <div class="card-header">
            <span>验证状态</span>
          </div>
        </template>

        <div class="verification-status">
          <el-timeline style="max-width: 600px">
            <el-timeline-item timestamp="2018/4/12" placement="top">
              <el-card class="timeline_card">
                <h4>Update Github template</h4>
                <p>Tom committed 2018/4/12 20:46</p>
              </el-card>
            </el-timeline-item>
            <el-timeline-item timestamp="2018/4/3" placement="top">
              <el-card class="timeline_card">
                <h4>Update Github template</h4>
                <p>Tom committed 2018/4/3 20:46</p>
              </el-card>
            </el-timeline-item>
            <el-timeline-item timestamp="2018/4/2" placement="top">
              <el-card class="timeline_card">
                <h4>Update Github template</h4>
                <p>Tom committed 2018/4/2 20:46</p>
              </el-card>
            </el-timeline-item>
          </el-timeline>
        </div>
      </el-card> -->

      <div style="flex: 1">
        <div class="resource-base">
          <el-card>
            <template #header>
              <div class="card-header">
                <span>基础信息</span>
              </div>
            </template>
            <div class="base-container">
              <div class="log-item">
                <span class="log-time">状态：</span>
                <span class="log-content">
                  <div
                    :class="{
                      circle: true,
                      redBg: monitorData.status === 2,
                      greenBg: monitorData.status === 1,
                    }"
                  ></div>
                  <div
                    :class="{
                      red: monitorData.status === 2,
                      green: monitorData.status === 1,
                    }"
                  >
                    {{
                      status[monitorData.status] &&
                      status[monitorData.status].name
                    }}
                  </div>
                </span>
              </div>
              <div class="log-item">
                <span class="log-time">集群：</span>
                <span class="log-content">{{ monitorData.clusterName }}</span>
              </div>
              <div class="log-item">
                <span class="log-time">计算节点：</span>
                <span class="log-content">{{ monitorData.computerName }}</span>
              </div>
              <div class="log-item">
                <span class="log-time">镜像/靶标：</span>
                <el-tooltip
                  :content="monitorData.baseImage"
                  placement="top"
                  effect="light"
                >
                  <span class="text-ellipsis">{{ monitorData.baseImage }}</span>
                </el-tooltip>
              </div>
              <div class="log-item">
                <span class="log-time">场景：</span>
                <el-tooltip
                  :content="monitorData.sceneName"
                  placement="top"
                  effect="light"
                >
                  <span class="text-ellipsis">{{ monitorData.sceneName }}</span>
                </el-tooltip>
              </div>
            </div>
          </el-card>
          <el-card>
            <template #header>
              <div class="card-header">
                <span>资源利用</span>
              </div>
            </template>
            <div class="base-container">
              <div class="log-item">
                <span class="log-time">CPU利用率：</span>
                <div class="log-content" style="width: 85%" v-if="monitorData.cpuRate && monitorData.cpuRate.length>0">
                  <el-progress
                    :percentage="monitorData.cpuRate[monitorData.cpuRate.length-1]"
                    :stroke-width="20"
                    striped
                    :text-inside="true"
                    style="width: 100%"
                  />
                </div>
              </div>
              <div class="log-item">
                <span class="log-time">内存利用率：</span>
                <div class="log-content" style="width: 85%" v-if="monitorData.memoryRate && monitorData.memoryRate.length>0">
                  <el-progress
                    :percentage="monitorData.memoryRate[monitorData.memoryRate.length-1]"
                    :stroke-width="20"
                    striped
                    :text-inside="true"
                    style="width: 100%"
                  />
                </div>
              </div>
              <div class="resource-item">
                <span class="log-time">IPS：</span>
                <span class="log-content">
                  <div v-for="ips in monitorData.ips">{{ ips.mac }}</div>
                </span>
              </div>
            </div>
          </el-card>
          <el-card>
            <template #header>
              <div class="card-header">
                <span>备注</span>
              </div>
            </template>
            <div class="chart-container">
              {{ monitorData.remarks }}
            </div>
          </el-card>
        </div>
        <!-- 资源使用监控 -->
        <div class="resource-monitor">
          <el-card>
            <template #header>
              <div class="card-header">
                <span>CPU 使用率</span>
                <span class="value-text"
                  >{{ monitorData.cpuUsage || "0" }}%</span
                >
              </div>
            </template>
            <div class="chart-container">
              <div ref="cpuChartRef" class="chart"></div>
            </div>
          </el-card>

          <el-card>
            <template #header>
              <div class="card-header">
                <span>内存使用率</span>
                <span class="value-text"
                  >{{ monitorData.memoryUsage || "0" }}%</span
                >
              </div>
            </template>
            <div class="chart-container">
              <div ref="memoryChartRef" class="chart"></div>
            </div>
          </el-card>
        </div>

        <!-- 网络流量监控 -->
        <!--<el-card>
          <template #header>
            <div class="card-header">
              <span>网络流量</span>
            </div>
          </template>
          <div class="chart-container">
            <div ref="networkChartRef" class="chart network-chart"></div>
          </div>
        </el-card>-->

        <!-- 实时日志 -->
        <el-card>
          <template #header>
            <div class="card-header">
              <span>日志记录</span>
              <!--<div class="log-actions">
                 <el-dropdown @command="handleLogFilter">
                  <el-button type="default" size="small">
                    筛选
                    <el-icon class="el-icon--right"><arrow-down /></el-icon>
                  </el-button>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item command="all">全部</el-dropdown-item>
                      <el-dropdown-item command="info">信息</el-dropdown-item>
                      <el-dropdown-item command="warning"
                        >警告</el-dropdown-item
                      >
                      <el-dropdown-item command="error">错误</el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown> 
                <el-button type="primary" size="small" @click="exportLogs"
                  >导出</el-button
                >
              </div>-->
            </div>
          </template>

          <div class="logs-container">
            <div
              v-for="(log, index) in logsData"
              :key="log.id"
              class="log-item"
            >
              <span class="log-time">第{{ index + 1 }}条：</span>
              <span class="log-content">{{
                JSON.parse(log.info).message
                  ? JSON.parse(log.info).message
                  : "-"
              }}</span>
            </div>
            <div v-if="filteredLogs.length === 0" class="empty-logs">
              暂无日志记录
            </div>
          </div>
        </el-card>
      </div>
    </div>

    <!-- 漏洞详情弹窗 -->
    <VulnDetailDialog
      v-if="detailVisible"
      v-model="detailVisible"
      :vuln-data="currentVulnData"
      @closed="handleDetailClosed"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, onBeforeUnmount } from "vue";
import { ArrowDown } from "@element-plus/icons-vue";
import VulnDetailDialog from "@/components/vulnDetailDialog/index.vue";
import * as echarts from "echarts/core";
import { LineChart } from "echarts/charts";
import {
  TooltipComponent,
  GridComponent,
  LegendComponent,
} from "echarts/components";
import { useCommonStore } from "@/stores/common";
import { CanvasRenderer } from "echarts/renderers";
import { ElMessage } from "element-plus";
import { getEnvironmentInfo, getVulnTaskDetail } from "@/api/topo";
import { useRouter } from "vue-router";
import { getVulnDetail } from "@/api/vulnVerification";

const { getTaskId, getQemuId, getVulnTitle, getVulnType, getTaskName } = useCommonStore();
const router = useRouter();
const ID = router.currentRoute.value.query.id || getTaskId();
const vuln_title = router.currentRoute.value.query.vuln_title || getVulnTitle();
const env_type = router.currentRoute.value.query.env_type || getVulnType();
const node_env_id = router.currentRoute.value.query.node_env_id || getQemuId();
const monitorData = ref({});
const options = ref([
  { value: "env1", label: "验证环境1" },
  { value: "env2", label: "验证环境2" },
  { value: "env3", label: "验证环境3" },
]);
const status = [
  { name: "停止" },
  {
    name: "运行",
  },
  { name: "停止" },
];
// 获取环境cpu、内存信息
const getEnvironmentInfoFunc = async () => {
  const res = await getEnvironmentInfo(node_env_id, env_type);
  if (res.code === 200) {
    monitorData.value = res.data;
    initCharts();
  }
};
const value = ref("");

// 注册必需的组件
echarts.use([
  LineChart,
  TooltipComponent,
  GridComponent,
  LegendComponent,
  CanvasRenderer,
]);

// 引用和状态
const cpuChartRef = ref(null);
const memoryChartRef = ref(null);
const networkChartRef = ref(null);
const cpuChart = ref(null);
const memoryChart = ref(null);
const networkChart = ref(null);
const logFilter = ref("all");
const monitorInterval = ref(null);
const logsInterval = ref(null);
const logsData = ref([]);

// 日志数据
const logs = ref([
  { time: "10:00:00", level: "info", content: "启动验证进程" },
  { time: "10:00:01", level: "info", content: "加载验证环境配置" },
  { time: "10:00:30", level: "info", content: "开始执行漏洞验证" },
  { time: "10:00:45", level: "warning", content: "检测到异常网络连接" },
  { time: "10:01:00", level: "error", content: "目标端口无响应" },
]);

// 过滤后的日志
const filteredLogs = computed(() => {
  if (logFilter.value === "all") {
    return logs.value;
  }
  return logs.value.filter((log) => log.level === logFilter.value);
});

// 获取漏洞详情数据
const getVulnDetailFn = async (name) => {
  try {
    const res = await getVulnDetail({exploit: name});
    if (res.code === 200) {
      currentVulnData.value = res?.data || {}
      detailVisible.value = true;
    }
  } catch (error) {
    currentVulnData.value = {}
  }
}

// 初始化图表
const initCharts = () => {
  // CPU 图表
  cpuChart.value = echarts.init(cpuChartRef.value);
  const cpuOption = {
    tooltip: {
      trigger: "axis",
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      containLabel: true,
    },
    xAxis: {
      type: "category",
      data: monitorData.value.rateTime,
      boundaryGap: false,
    },
    yAxis: {
      type: "value",
      min: 0,
      max: 10,
      name: "%",
    },
    series: [
      {
        name: "CPU",
        type: "line",
        data: monitorData.value.cpuRate,
        areaStyle: {
          color: {
            type: "linear",
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              {
                offset: 0,
                color: "rgba(75, 192, 192, 0.8)",
              },
              {
                offset: 1,
                color: "rgba(75, 192, 192, 0.1)",
              },
            ],
          },
        },
        itemStyle: {
          color: "#4bc0c0",
        },
        smooth: true,
      },
    ],
  };
  cpuChart.value.setOption(cpuOption);

  // 内存图表
  memoryChart.value = echarts.init(memoryChartRef.value);
  const memoryOption = {
    tooltip: {
      trigger: "axis",
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      containLabel: true,
    },
    xAxis: {
      type: "category",
      data: monitorData.value.rateTime,
      boundaryGap: false,
    },
    yAxis: {
      type: "value",
      min: 0,
      max: 10,
      name: "%",
    },
    series: [
      {
        name: "内存",
        type: "line",
        data: monitorData.value.memoryRate,
        areaStyle: {
          color: {
            type: "linear",
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              {
                offset: 0,
                color: "rgba(116, 119, 231, 0.8)",
              },
              {
                offset: 1,
                color: "rgba(116, 119, 231, 0.1)",
              },
            ],
          },
        },
        itemStyle: {
          color: "#7477e7",
        },
        smooth: true,
      },
    ],
  };
  memoryChart.value.setOption(memoryOption);

  // 网络流量图表
  // networkChart.value = echarts.init(networkChartRef.value);
  // const networkOption = {
  //   tooltip: {
  //     trigger: "axis",
  //   },
  //   legend: {
  //     data: ["上行", "下行"],
  //   },
  //   grid: {
  //     left: "3%",
  //     right: "4%",
  //     bottom: "3%",
  //     containLabel: true,
  //   },
  //   xAxis: {
  //     type: "category",
  //     boundaryGap: false,
  //     data: monitorData.value.rateTime,
  //   },
  //   yAxis: {
  //     type: "value",
  //     name: "MB/s",
  //   },
  //   series: [
  //     {
  //       name: "上行",
  //       type: "line",
  //       stack: "Total",
  //       data: [
  //         0.5, 0.8, 1.2, 2.5, 2.8, 3.0, 3.8, 4.5, 5.0, 6.2, 4.8, 4.0, 3.5, 2.9,
  //         3.5, 4.0, 4.5, 5.0, 5.5, 7.0, 6.8, 6.0, 5.0, 4.0, 3.0, 2.0, 1.0, 1.5,
  //         2.0, 2.5,
  //       ],
  //       areaStyle: {
  //         color: {
  //           type: "linear",
  //           x: 0,
  //           y: 0,
  //           x2: 0,
  //           y2: 1,
  //           colorStops: [
  //             {
  //               offset: 0,
  //               color: "rgba(58, 184, 147, 0.8)",
  //             },
  //             {
  //               offset: 1,
  //               color: "rgba(58, 184, 147, 0.1)",
  //             },
  //           ],
  //         },
  //       },
  //       itemStyle: {
  //         color: "#3ab893",
  //       },
  //       smooth: true,
  //     },
  //     {
  //       name: "下行",
  //       type: "line",
  //       stack: "Total",
  //       data: [
  //         0.3, 0.5, 0.9, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 3.9, 3.5, 3.0, 2.5,
  //         3.0, 3.5, 3.0, 4.0, 4.5, 5.0, 4.5, 4.0, 3.5, 3.0, 2.5, 2.0, 1.5, 0.9,
  //         0.5, 0.3,
  //       ],
  //       areaStyle: {
  //         color: {
  //           type: "linear",
  //           x: 0,
  //           y: 0,
  //           x2: 0,
  //           y2: 1,
  //           colorStops: [
  //             {
  //               offset: 0,
  //               color: "rgba(86, 152, 235, 0.8)",
  //             },
  //             {
  //               offset: 1,
  //               color: "rgba(86, 152, 235, 0.1)",
  //             },
  //           ],
  //         },
  //       },
  //       itemStyle: {
  //         color: "#5698eb",
  //       },
  //       smooth: true,
  //     },
  //   ],
  // };
  // networkChart.value.setOption(networkOption);

  // 窗口大小变化时重绘图表
  window.addEventListener("resize", handleResize);
};

// 处理窗口大小变化
const handleResize = () => {
  cpuChart.value && cpuChart.value.resize();
  memoryChart.value && memoryChart.value.resize();
  networkChart.value && networkChart.value.resize();
};

// 格式化时间
const formatTime = (timeStr) => {
  return timeStr || "--:--";
};

// 获取日志样式类
const getLogClass = (level) => {
  return {
    "log-info": level === "info",
    "log-warning": level === "warning",
    "log-error": level === "error",
  };
};

// 处理日志过滤
const handleLogFilter = (command) => {
  logFilter.value = command;
};

// 导出日志
const exportLogs = () => {
  // 导出日志逻辑
  ElMessage.success("日志导出成功");
};

// 获取漏洞验证详情
const getVulnTaskDetailFunc = async () => {
  const res = await getVulnTaskDetail(ID);
  if (res.code === 200) {
    logsData.value = res.data;
  }
};
// 查看详情
const currentVulnData = ref(null);
const detailVisible = ref(false);
const handleViewDetails = (row) => {
  getVulnDetailFn(vuln_title);  
};
// 详情弹窗关闭
const handleDetailClosed = () => {
  detailVisible.value = false;
};

// 组件挂载时初始化
onMounted(() => {
  getVulnTaskDetailFunc();
  getEnvironmentInfoFunc();  
  // 初始化图表和数据
  // initCharts();
  // updateMonitorData();
  // initIntervals();
});

// 组件卸载前清理
onBeforeUnmount(() => {
  window.removeEventListener("resize", handleResize);

  // 销毁图表实例
  cpuChart.value && cpuChart.value.dispose();
  memoryChart.value && memoryChart.value.dispose();
  networkChart.value && networkChart.value.dispose();
});
</script>

<style lang="scss" scoped>
.environment-monitor {
  padding: 20px;
  .header-actions {
    background-color: var(--card-bg);
    border-radius: 4px;
    padding: 16px;
    margin-bottom: 20px;
  }

  .selectBox {
    margin-right: 50px;
  }

  ::v-deep {
    .el-card__body {
      width: 100%;
      display: flex;
      > div {
        > span {
          margin-right: 15px;
        }
      }
    }
  }

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .value-text {
      font-size: 16px;
      font-weight: bold;
    }
  }

  .verification-status {
    padding: 10px 0;
  }

  .resource-monitor {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 15px;
    margin-bottom: 15px;
  }
  .resource-base {
    display: grid;
    grid-template-columns: 1fr 2fr 1fr;
    gap: 15px;
    margin-bottom: 15px;
  }
  .chart-container {
    width: 100%;

    .chart {
      height: 250px;
      width: 100%;
    }

    .network-chart {
      height: 300px;
    }
  }

  .logs-container {
    width: 100%;
    height: 300px;
    overflow-y: auto;
    font-family: monospace;

    .log-item {
      padding: 4px 8px;
      border-bottom: 1px solid #f0f0f0;
      font-size: 13px;
      display: flex;

      .log-time {
        color: #909399;
        width: 80px;
        flex-shrink: 0;
      }

      .log-content {
        flex: 1;
      }

      &.log-info {
        color: #606266;
      }

      &.log-warning {
        color: #e6a23c;
        background-color: rgba(230, 162, 60, 0.05);
      }

      &.log-error {
        color: #f56c6c;
        background-color: rgba(245, 108, 108, 0.05);
      }
    }

    .empty-logs {
      text-align: center;
      color: #909399;
      padding: 40px 0;
    }
  }

  .log-actions {
    display: flex;
    gap: 10px;
  }
}
.base-container {
  width: 100%;
  .log-item {
    display: flex;
    justify-content: space-between;
    margin-bottom: 10px;
    .log-content {
      display: flex;
      gap: 10px;
      justify-content: flex-end;
      align-items: center;
      font-size: 14px;
    }
  }
  .resource-item {
    .log-content {
      display: grid;
      gap: 10px;
      grid-template-columns: repeat(5, 1fr);
    }
  }
}
.circle {
  width: 15px;
  height: 15px;
  border-radius: 50%;
}
.green {
  color: #bcda5f;
}
.greenBg {
  background-color: #bcda5f;
}
.red {
  color: #da5f5f;
}
.redBg {
  background-color: #da5f5f;
}
.text-ellipsis {
  width: 76%;
  white-space: nowrap; /* 防止文本换行 */
  overflow: hidden; /* 隐藏溢出的内容 */
  text-overflow: ellipsis; /* 显示省略符号来代表被修剪的文本 */
  font-size: 14px;
  text-align: right;
}
</style>
